import React from 'react';
import { 
  Upload, 
  Button, 
  Select,
  Typography,
  Alert,
  Space,
  message,
  Progress,
  Modal,
  Card
} from 'antd';
import { 
  LoadingOutlined,
  FileWordOutlined,
  FilePptOutlined,
  InboxOutlined,
  DeleteOutlined,
  DownloadOutlined
} from '@ant-design/icons';
import { pdfService } from '../services/pdfService';
import type { UploadProps } from 'antd';
import styles from './PDFConverter.module.css';
import PageHeader from './PageHeader';
import { APIError } from '../services/pdfService';

const { Dragger } = Upload;
const { Option } = Select;
const { Text, Title } = Typography;

interface PDFConverterProps {
  type: 'word' | 'ppt';
}

const PDFConverter: React.FC<PDFConverterProps> = ({ type }) => {
  const [selectedFile, setSelectedFile] = React.useState<File | null>(null);
  const [convertType, setConvertType] = React.useState<'word' | 'ppt'>('word');
  const [converting, setConverting] = React.useState(false);
  const [error, setError] = React.useState<string>('');
  const [progress, setProgress] = React.useState(0);
  const [convertedFile, setConvertedFile] = React.useState<{
    blob: Blob;
    fileName: string;
  } | null>(null);
  const [showDownloadModal, setShowDownloadModal] = React.useState(false);

  const title = type === 'word' ? 'PDF转Word' : 'PDF转PPT';

  const handleFileSelect = (info: any) => {
    const file = info.file;
    if (!file) return;

    setError('');
    setProgress(0);
    setConvertedFile(null);

    if (!pdfService.validatePDFFile(file)) {
      setError('请上传有效的PDF文件（小于50MB）');
      return;
    }

    setSelectedFile(file);
  };

  const handleConvert = async () => {
    if (!selectedFile) {
      message.warning('请先选择文件');
      return;
    }

    try {
      setConverting(true);
      setError('');
      setProgress(0);

      // 直接调用转换并下载
      await pdfService.convertPDF(selectedFile, type);
      
      setProgress(100);
      message.success('转换成功！');
    } catch (error) {
      let errorMessage = '转换失败';
      
      if (error instanceof APIError) {
        switch (error.status) {
          case 413:
            errorMessage = '文件太大，请上传小于50MB的文件';
            break;
          case 415:
            errorMessage = '不支持的文件类型';
            break;
          case 422:
            errorMessage = '文件验证失败，请确保文件格式正确';
            break;
          default:
            errorMessage = error.message;
        }
      }

      setError(errorMessage);
      message.error(errorMessage);
    } finally {
      setConverting(false);
    }
  };

  const handleRedownload = async () => {
    if (!convertedFile) return;

    const hide = message.loading('准备下载...', 0);
    
    try {
      const success = await pdfService.saveFileWithDialog(
        convertedFile.blob, 
        convertedFile.fileName
      );

      hide();
      
      if (success) {
        message.success('文件已保存');
      }
    } catch (error) {
      hide();
      message.error('文件保存失败，请重试');
      console.error('Download error:', error);
    }
  };

  const uploadProps: UploadProps = {
    name: 'file',
    multiple: false,
    accept: '.pdf',
    showUploadList: false,
    beforeUpload: () => false,
    onChange: handleFileSelect,
  };

  return (
    <div className={styles.container}>
      <PageHeader title={title} />
      <Card className={styles.converterCard}>
        <Title level={4} className={styles.cardTitle}>
          PDF转换
          <Select 
            value={convertType} 
            onChange={(value: 'word' | 'ppt') => {
              setConvertType(value);
              setError('');
              setProgress(0);
              setConvertedFile(null);
            }}
            className={styles.formatSelect}
          >
            <Option value="word">转Word</Option>
            <Option value="ppt">转PPT</Option>
          </Select>
        </Title>

        <div className={styles.uploadSection}>
          {!selectedFile ? (
            <Dragger {...uploadProps} className={styles.draggerContainer}>
              <p className="ant-upload-drag-icon">
                <InboxOutlined className={styles.uploadIcon} />
              </p>
              <p className={styles.uploadText}>
                点击或拖拽PDF文件到此区域
              </p>
              <p className={styles.uploadHint}>
                支持单个PDF文件，大小不超过50MB
              </p>
            </Dragger>
          ) : (
            <div className={styles.fileInfo}>
              <div className={styles.fileDetails}>
                <span className={styles.fileName}>{selectedFile.name}</span>
                <span className={styles.fileSize}>
                  {(selectedFile.size / (1024 * 1024)).toFixed(2)}MB
                </span>
              </div>
              <Space>
                <Button 
                  icon={<DeleteOutlined />}
                  onClick={() => {
                    setSelectedFile(null);
                    setError('');
                    setProgress(0);
                    setConvertedFile(null);
                  }}
                >
                  删除
                </Button>
                <Button
                  type="primary"
                  icon={converting ? <LoadingOutlined /> : (
                    convertType === 'word' ? <FileWordOutlined /> : <FilePptOutlined />
                  )}
                  onClick={handleConvert}
                  loading={converting}
                  disabled={!!error}
                >
                  {converting ? '转换中...' : '开始转换'}
                </Button>
              </Space>
            </div>
          )}
        </div>

        {error && (
          <Alert
            message="错误"
            description={error}
            type="error"
            showIcon
            className={styles.alert}
          />
        )}

        {converting && (
          <div className={styles.progressContainer}>
            <Progress 
              percent={progress} 
              status={progress === 100 ? "success" : "active"}
              strokeColor={{
                '0%': '#108ee9',
                '100%': '#87d068',
              }}
            />
          </div>
        )}

        {convertedFile && (
          <Alert
            message={
              <Space size="middle" align="center" className={styles.convertedInfo}>
                <Text type="success">
                  转换完成
                </Text>
                <Button 
                  type="link"
                  icon={<DownloadOutlined />}
                  onClick={handleRedownload}
                >
                  重新下载
                </Button>
              </Space>
            }
            type="success"
            showIcon
          />
        )}
      </Card>
    </div>
  );
};

export default PDFConverter; 